/* -------------------------------------------------------------------------- */
/*                              passport 验证用户名密码
/* -------------------------------------------------------------------------- */

import passport from 'passport';
import LocalStrategy from 'passport-local';
import crypto from 'crypto';
import UserService from "@src/services/user";

passport.use(new LocalStrategy.Strategy({
  // 默认从 req.body 中取
  usernameField: 'username',
  passwordField: 'password',
},
  async function (username, password, done) {
    try {
      const row = await UserService.getUser({ username });
      if (!row) {
        return done(null, false, { message: '用户未注册' });
      }

      // ⚠️ 重要：将数据库中的十六进制字符串转换回 Buffer
      const saltBuffer = Buffer.from(row.salt, 'hex');
      const storedPasswordBuffer = Buffer.from(row.password, 'hex');

      // 使用同步方法加密用户输入的密码（返回 Buffer）
      const hashedPasswordBuffer = crypto.pbkdf2Sync(password, saltBuffer, 310000, 32, 'sha256');

      // 使用时间安全的比较方法（防止时序攻击）
      if (!crypto.timingSafeEqual(hashedPasswordBuffer, storedPasswordBuffer)) {
        return done(null, false, { message: '用户名或者密码错误' });
      }

      return done(null, row);
    } catch (error) {
      console.error('Passport authentication error:', error);
      return done(error);
    }
  }
));

passport.serializeUser(function (user: any, cb) {
  process.nextTick(function () {
    cb(null, { id: user.id, username: user.name, role_id: user.role_id });
  });
});

passport.deserializeUser(function (user: any, cb) {
  console.log("deserializeUser", user);
  process.nextTick(function () {
    return cb(null, user);
  });
});

export default passport;
